<?php

class Ads_IndexController extends Zend_Controller_Action {

    private $_translate = null;


    public function init() {
        $this->_translate = Zend_Registry::get('Zend_Translate');
        $userValidation = new Validations_User();
        $valid = $userValidation->hasidentity();
        if ($valid && $userValidation->getUserTypeId() == 2) {
            
        } else {
            $this->_redirect('/users/login');
        }
    }

    public function indexAction() {
        
    }

    public function placeadAction() {
        $form = new Ads_Form_Placead();
        $this->view->form = $form;

        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();
                $zipDb = new Ads_Model_Zipcode();
                $stateObj = $zipDb->getStateNameFromZipId($values['zipcode']);
                $values['state'] = $stateObj[0]['id'];                
                #vacant-date
                if ($values['vacant'] != 2) {
                    $values['date'] = '';
                }
                #pets
                if ($values['pets'] != 0) {
                    $values['petsData'] = '';
                }
//                $photoArray = $values['photo'];
//                $photoArrayKey = array_keys($photoArray);
                $photoArray = array();
                $db = new Ads_Model_Rentdetails();
                $userValidation = new Validations_User();
                $userId = $userValidation->getUserId();
                $date = date('Y-m-d', date('U'));
                $i = 0;
                $adapter = $form->photo->getTransferAdapter();
                foreach ($adapter->getFileInfo() as $info) {
                    $extension = pathinfo($info['name'], PATHINFO_EXTENSION);
                    $basename = basename($info['name'], '.' . $extension);
                    $newName = $userId . '_' . md5($basename) . '_' . md5(time()) . '.' . $extension;
                    $nName = iconv('utf-8', 'cp1251', $newName);
                    $adapter->addFilter('Rename', array(
                        'target' => $nName,
//                        'source' => $info['tmp_name'],
                        'overwrite' => true
                    ));
                    $adapter->receive($info['name']);
                    //$k = $photoArrayKey[$i];
                    //$photoArray[$k] = $nName;
                    array_push($photoArray, $nName);
                    $i++;
                }
                $values['photo'] = $photoArray;
                $rent_details = $this->convertFormToJson($values);
                $insertId = $db->createNewProperty(array(
                    'user_id' => $userId,
                    'details' => $rent_details,
                    'date' => $date,
                    'banned' => false
                ));
                $this->notificationAction($insertId);
                $this->_redirect('/users/ads');
            }
        }
    }

    /**
     * This function will convert form values to Json format.
     * @param type $values   
     *
     */
    public function convertFormToJson($values) {
        return json_encode(array('details' => $values));
    }

    public function showuseradsAction() {
        $userValidation = new Validations_User();
        $userId = $userValidation->getUserId();
        $db = new Ads_Model_Rentdetails();
        $details = $db->getRentDetailsByUserId($userId);
        $this->view->details = $details;
    }

    public function blockunblockAction() {
        $propertyId = $this->getinputidAction();
        $db = new Ads_Model_Rentdetails();
        $blocked = false;
        if ($db->isBlocked($propertyId)) {
            $blocked = false;
        } else {
            $blocked = true;
        }
        $data = array(
            'banned' => $blocked
        );
        $db->updatePropertyDetails($data, $propertyId);
        $this->_redirect('/users/ads');
    }

    public function updateAction() {
        $propertyId = $this->getinputidAction();
        $form = new Ads_Form_Placead();
        $db = new Ads_Model_Rentdetails();
        $this->view->proId = $propertyId;
        $details = $db->getFormatedRentDetailsByPropertyId($propertyId);
        $form->propertyId->setValue($propertyId);
        $form->adTitle->setValue($details->adTitle);
        $form->adDesc->setValue($details->adDesc);
        $form->zipcode->setValue($details->zipcode);
        $form->streetName->setValue($details->streetName);
        $form->houseno->setValue($details->houseno);
        $form->floor->setValue($details->floor);
        $form->vacant->setValue($details->vacant);
        $form->date->setValue($details->date);
        $form->propertyType->setValue($details->propertyType);
        $form->rentalPeriod->setValue($details->rentalPeriod);
        $form->area->setValue($details->area);
        $form->rooms->setValue($details->rooms);
        $form->rent->setValue($details->rent);
        $form->furnishType->setValue($details->furnishType);
        $form->depositeSelect->setValue($details->depositeSelect);
        $form->depositeValue->setValue($details->depositeValue);
        $form->prerentSelect->setValue($details->prerentSelect);
        $form->prerentValue->setValue($details->prerentValue);
        $form->fixedExpense->setValue($details->fixedExpense);
        $form->pets->setValue($details->pets);
        $form->petsData->setValue($details->petsData);
        $form->submit->setLabel($this->_translate->_('update_property'));
        $this->view->form = $form;
        $this->view->photos = $db->getPhotoArrayFromJson($details);


        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();
                $zipDb = new Ads_Model_Zipcode();
                $stateObj = $zipDb->getStateNameFromZipId($values['zipcode']);
                $values['state'] = $stateObj[0]['id'];
                #vacant-date
                if ($values['vacant'] != 2) {
                    $values['date'] = '';
                }
                #pets
                if ($values['pets'] != 0) {
                    $values['petsData'] = '';
                }
                $details0 = $db->getFormatedRentDetailsByPropertyId($values['propertyId']);
                $photoArray = $db->getPhotoArrayFromJson($details0);
                $userValidation = new Validations_User();
                $userId = $userValidation->getUserId();
                $date = date('Y-m-d', date('U'));
                if ($values['photo'] != null) {
                    $i = 0;
                    $adapter = $form->photo->getTransferAdapter();
                    foreach ($adapter->getFileInfo() as $info) {
                        $extension = pathinfo($info['name'], PATHINFO_EXTENSION);
                        $basename = basename($info['name'], '.' . $extension);
                        $newName = $userId . '_' . md5($basename) . '_' . md5(time()) . '.' . $extension;
                        $nName = iconv('utf-8', 'cp1251', $newName);
                        $adapter->addFilter('Rename', array(
                            'target' => $nName,
//                        'source' => $info['tmp_name'],
                            'overwrite' => true
                        ));
                        $adapter->receive($info['name']);
                        //$k = $photoArrayKey[$i];
                        //$photoArray[$k] = $nName;
                        array_push($photoArray, $nName);
                        $i++;
                    }
                }
                $values['photo'] = $photoArray;
                $rent_details = $this->convertFormToJson($values);
                $newdata = array(
                    'user_id' => $userId,
                    'details' => $rent_details,
                    'date' => $date,
                    'banned' => false
                );
                $db->updatePropertyDetails($newdata, $values['propertyId']);
                //$this->notificationAction($insertId);
                $this->_redirect('/users/ads/' . $values['propertyId'] . '/edit');
            }
        }
    }

    public function deleteadsAction() {
        $propertyId = $this->getinputidAction();
        $db = new Ads_Model_Rentdetails();
        $db->deleteProperty($propertyId);
        $this->_redirect("/users/ads");
    }

    public function deleteimageAction() {
        #get input.        
        $filters = array('id' => array('StringTrim'));
        $validators = array();
        $input = new Zend_Filter_Input($filters, $validators);
        $input->setData($this->getRequest()->getParams());
        $getID = $input->id;
//        #do operation
        $ids = explode("_", $getID);
        $db = new Ads_Model_Rentdetails();
        $rentDetailsBySr = $db->getRentDetailsBySr($ids[0]);
        $details = $rentDetailsBySr[0]['details'];
        $djson = json_decode($details);
        $photoArray = $db->getPhotoArrayFromJson($djson->details);
        $newArray = array();
        $localI = 0;
        foreach ($photoArray as $photo) {
            if ($localI != $ids[1]) {
                array_push($newArray, $photo);
            }
            $localI++;
        }
        $djson->details->photo = $newArray;
        $dataNew = array('details' => json_encode($djson));
        $db->updatePropertyDetails($dataNew, $ids[0]);
        $this->_redirect('/users/ads/' . $ids[0] . '/edit');
    }

    /**
     * Get Property ID.    
     *
     */
    public function getinputidAction() {
        $filters = array(
            'id' => array('HtmlEntities', 'StripTags', 'StringTrim')
        );
        $validators = array(
            'id' => array('Int')
        );
        $input = new Zend_Filter_Input($filters, $validators);
        $input->setData($this->getRequest()->getParams());
        $id = $input->id; //property id
        return $id;
    }

    public function searchresultAction() {
        
    }

    public function showmessagesAction() {
        $userValidation = new Validations_User();
        $ownerId = $userValidation->getUserId();
        $db = new Ads_Model_Contactowner();
        $details = $db->getByOwnerId($ownerId);
        $this->view->details = $details;
    }

    public function searchsettingAction() {
        $userValidation = new Validations_User();
        $userId = $userValidation->getUserId();
        $db0 = new Users_Model_Users();
        $user = $db0->getUser($userId);
        $searchJson = $user[0]['search_settings'];
        $details = null;
        if ($searchJson != null) {
            $details = $this->getSearchSettingsDecodedAction($searchJson);
        }
        $form = new Ads_Form_Searchsettings();
        $form->main($details);
        $this->view->form = $form;

        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();
                $json = json_encode(array('details' => $values));
                $db = new Users_Model_Users();
                $db->updateUser(array(
                    'search_settings' => $json
                        ), $userId);
                $this->_redirect('/ads/index/success');
            }
        }
    }

    public function successAction() {
        // action body
    }

    public function notificationAction($insertId) {
        $rentDetailsDb = new Ads_Model_Rentdetails();
        $rentDetailsData = $rentDetailsDb->getRentDetailsBySr($insertId);
        $propertyDetails = $this->getSearchSettingsDecodedAction($rentDetailsData[0]['details']);
        $userDb = new Users_Model_Users();
        $users = $userDb->getValidUsers();
        foreach ($users as $user) {
            $userId = $user['id'];
            $json = $user['search_settings'];
            if ($json != null) {
                $userSearchDetails = $this->getSearchSettingsDecodedAction($json);
                $sDb = new Validations_Searchforusersettings();
                if ($sDb->search($propertyDetails, $userSearchDetails)) {
                    echo 'Property Matched';
                    $linkPath = 'http://' . $_SERVER['SERVER_NAME'] . '/property/details/' . $insertId;
                    //send email to user.
                    $api = new Sendgrid_Mail();
                    $emailData = array(
                        'toEmail' => $user['email'],
                        'toName' => $user['name'],
                        'subject' => 'Property Matched as per your search settings',
                        'body' => '<html>Welcome ' . $user['name'] . ',<br>One property is posted as per your search settngs.<br>See details about that property: <a href="' . $linkPath . '">' . $propertyDetails->adTitle . '</a></html>'
                    );
                    $api->sendMail($emailData);
                } else {
                    echo 'property not matched';
                }
            }
        }
    }

    public function getSearchSettingsDecodedAction($json) {
        $decode = json_decode($json);
        return $decode->details;
    }

}

